<template>
  <div class="dialog">
    <el-dialog
      title="维修处理"
      :visible.sync="showDialog"
      width="35%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="维修结果：" class="w100p" prop="taskStatus">
          <el-select
            v-model="formData.taskStatus"
            clearable
            filterable
            placeholder="维修结果选择"
          >
            <el-option
              v-for="item of taskStatusArr"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维修日期 ：" class="w100p" prop="repairDate">
          <el-date-picker
            v-model="formData.repairDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
          />
        </el-form-item>

        <el-form-item label="开始时间 ：" class="w100p" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
                  :picker-options="startDatePicker"
            placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </el-form-item>

        <el-form-item label="结束时间 ：" class="w100p" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
                  :picker-options="endDatePicker"
            placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          />
        </el-form-item>

        <el-form-item label="工时 ：" class="w100p" prop="workingHours">
          <el-input
            v-model="formData.workingHours"
            placeholder="请输入工时"

            @input="($event) => {
            if($event.startsWith('0') && !$event.includes('.') && $event != 0){
              $set(formData, 'workingHours', $event.replace(/\b(0+)/gi,''))
            }else{
              $set(formData, 'workingHours', Math.abs($event))
            }}"
            clearable
          />
        </el-form-item>
        <el-form-item label="维修人：" class="w100p" prop="handUsername">
          <el-select
            v-model="formData.handUsername"
            clearable
            filterable
            placeholder="维修人选择"
          >
            <el-option
              v-for="item of userList"
              :key="item.userId"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备件消耗：" class="w100p">
          <div class="line-click" @click="addDeviceCodes()">
            <i class="el-icon-plus"></i>
          </div>
          <div class="hang-content">
            <div
              v-for="(key, index) in repairConsumeBOList"
              :key="index + 'deviceCode'"
              class="hang-content-one"
            >
              <el-select
                v-model="key.deviceCode"
                clearable
                filterable
                placeholder="备件选择"
              >
                <el-option
                  v-for="(item, indexk) of sparePartArr"
                  :key="item.sparePartsCode + 'spare' + indexk"
                  :label="item.sparePartsName"
                  :value="item.sparePartsCode"
                />
              </el-select>
              <el-input v-model="key.num" clearable placeholder="请填写数量" />
              <el-input
                v-model="key.cost"
                clearable
                placeholder="请填写维修费用"
              />
              <div class="line-click" @click="delDeviceCodes(index)">
                <i class="el-icon-minus"></i>
              </div>
            </div>
          </div>
        </el-form-item>
        <div class="repairFile">
          <el-form-item label="维修图片：" class="w100p">
            <!-- <el-upload
              ref="upload"
              class="upload-file"
              action
              multiple
              :on-remove="params => removePicture(params)"
              :http-request="params => addPicture(params)"
              :file-list="pictureList"
              accept=".png, .jpg, .jpeg, .pdf "
            >
              <el-button type="text" class="add-many">
                <i class="el-icon-plus"></i>
              </el-button>
            </el-upload> -->
            <UploadPics ref="UploadPics" accept=".jpg, .jpeg, .png" v-model="uploadPictureList" @input="handlerAddFileList($event, 'png')" @delectFileId="handlerDeleteId($event, 'png')">
            </UploadPics>
          </el-form-item>

          <el-form-item label="故障视频：" class="w100p">
              <!-- <el-upload
                ref="upload"
                class="upload-file"
                action
                multiple
                :on-remove="params => removeVideo(params)"
                :http-request="params => addVideo(params)"
                :file-list="uploadVideoList"
                accept=".mp4"
              >
                <el-button type="text" class="add-many">
                  <i class="el-icon-plus"></i>
                </el-button>
              </el-upload> -->
              <UploadPics ref="UploadPics" accept=".mp4" v-model="uploadVideoList" @input="handlerAddFileList($event, 'video')" @delectFileId="handlerDeleteId($event, 'video')">
            </UploadPics>
          </el-form-item>
        </div>
        <el-form-item label="处理过程：" class="w100p" prop="cost">
          <el-input
            v-model="formData.processMode"
            clearable
            placeholder="请输入处理过程"
          />
        </el-form-item>
        <el-form-item label="备注：" class="w100p" prop="remark">
          <el-input
            v-model="formData.remark"
            clearable
            :rows="2"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RepairHandleApi from "@/api/equip-repair-manage/repair-handle/index";
// import sparePartsInputApi from "@/api/spare-part-manage/spare-parts-input";
import sparePartsInputApi from "@/api/basic-info-manage/spare-parts-manage";
import userApi from "@/api/system-settings/user-manage";
import videoApi from "@/api/document/index";
import UploadPics from "@/components/UploadPics/upload-img-list.vue"
export default {
  name: "",
  components: {
    UploadPics
  },
  props: {
    // 弹框名称
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      uploadPictureList: [],
      pictureList: [],
      uploadVideoList: [],
      formData: {},
      repairConsumeBOList: [{ num: "", deviceCode: "", cost: "" }],
      rules: {
        repairDate: [
          {
            required: true,
            message: "请选择维修日期",
            trigger: ["change", "blur"]
          }
        ],
        handUsername: [
          {
            required: true,
            message: "请选择维修人",
            trigger: ["change", "blur"]
          }
        ],
        startTime: [
          {
            required: true,
            message: "请选择开始时间",
            trigger: ["change", "blur"]
          }
        ],
        endTime: [
          {
            required: true,
            message: "请选择结束时间",
            trigger: ["change", "blur"]
          }
        ],
        workingHours: [
          {
            required: true,
            message: "请输入工时",
            trigger: ["change", "blur"]
          }
        ],
        taskStatus: [
          {
            required: true,
            message: "请选择维修结果",
            trigger: ["change", "blur"]
          }
        ]
      },
      // 备件
      sparePartArr: [],
      taskStatusArr: ["维修完成", "维修失败"],
      showDialog: this.show,
      userList: [],
      equipmentVideoIdList: [],
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate()
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
      if (v) {
        this.formData = this.editObject;
        this.formData.taskStatus = "";
        this.repairConsumeBOList = [{ num: "", deviceCode: "", cost: "" }];
        this.uploadVideoList = [];
        this.equipmentVideoIdList = [];
        this.pictureList = [];
        this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      }
    },
    'formData.startTime': {
      handler(v) {
        if (v && this.formData.endTime) {
          this.$set(this.formData, 'workingHours', (this.getDaysBetween(v, this.formData.endTime) * 8).toFixed(0))
        }
      }
    },
    'formData.endTime': {
      handler(v) {
        if (v && this.formData.startTime) {
          this.$set(this.formData, 'workingHours', (this.getDaysBetween(this.formData.startTime, v) * 8).toFixed(0))
        }
      }
    }
  },
  created() {
    this.querySparePart();
    this.queryUserList();
  },
  mounted() {},
  methods: {
      /**
       * @description 两个时间相减获取天数
       * @param {string} path
       * @returns {Boolean}
       */
      getDaysBetween(startDate, enDate) {
        const sDate = Date.parse(startDate);
        const eDate = Date.parse(enDate);
        if (sDate > eDate) {
          return 0;
        }
        if (sDate === eDate) {
          return 1;
        }
        const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);
        return days;
      },
    // 添加-轮播图/视频
      handlerAddFileList(data, type){
      // console.log(data);
      if (type === 'png') {
        this.uploadPictureList = data.list;
      }
      if (type === 'video') {
        this.uploadVideoList = data.list;
        this.handleSuccessV(data.obj);
      }
      // if(this.form.fileList == null){
        // this.form.fileList = []
      // }
      // this.form.fileList.push(data.fileId)
    },
        // 限制前面日期不能低于后面日期
        beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.endTime) {
            //  如果结束时间不为空，则小于结束时间
            return new Date(self.formData.endTime).getTime() < time.getTime();
          } else {
            return time.getTime() >= Date.now() + 1 * 24 * 60 * 60 * 1000// 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.startTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.formData.startTime).getTime() > time.getTime();
          } else {
            return time.getTime() >= Date.now() - 1 * 24 * 60 * 60 * 1000// 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
     // 视频上传
     handleSuccessV(obj) {
      let that = this;
      // let fd = new FormData();
      // fd.append("file", this.modePicture);
      // fd.append("equipmentCode", this.editObject.equipmentCode);
      videoApi.addEquipmentVideoNew({
        equipmentCode: this.editObject.hitchInfoCode,
        filePath: obj.url,
        fileName: obj.fileName
      }).then((res) => {
        if (res.code === 1) {
          this.equipmentVideoIdList.push(res.data.equipmentVideoId);
        }
        else that.$message.error(res.msg);
      });
    },
    // 图片上传
    // handleSuccess(list, data) {
    //   let that = this;
    //   // let fd = new FormData();
    //   // fd.append("urlList", list.map(item => item.url));
    //   // list.forEach(item => fd.append("urlList", item.url));
    //   // fd.append("hitchInfoCode", this.editObject.hitchInfoCode);
    //   failureToReportApi.addPictureNew({
    //     hitchInfoCode: data ||  this.editObject.hitchInfoCode,
    //     urlList: list.map(item => item.url)
    //   }).then((res) => {
    //     if (res.code === 1) {
    //      //  that.$message.success("上传成功！");
    //      this.queryPicByCode(this.editObject.hitchInfoCode);
    //     }
    //     else that.$message.error(res.msg);
    //   });
    // },
    // 删除-轮播图/视频
    handlerDeleteId(file, type){
      // this.$confirm()
      this.$confirm(`确认删除该${type === 'png' ? '图片' :type === 'video'? '视频': '文件' }`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          // console.log(file)
          if (file.equipmentPictureId) {
            this.uploadPictureList.splice(this.uploadPictureList.findIndex(i => i.url == fileId), 1)
          } else if (file.equipmentVideoId) {
            videoApi.delVideoList(file.equipmnetVideoId).then((res) => {
            if (res.code === 1) this.$message.success("删除成功！");
            else this.$message.error(res.msg);
          });
            let fileId = file.url;
            this.uploadVideoList.splice(this.uploadVideoList.findIndex(i => i.url == fileId), 1)
        } else {
            if (type === "video") {
              let fileId = file.url;
              this.uploadVideoList.splice(
                this.uploadVideoList.findIndex(i => i.url == fileId),
                1
              );
            } else if (type === "png") {
              let fileId = file.url;
              this.uploadPictureList.splice(
                this.uploadPictureList.findIndex(i => i.url == fileId),
                1
              );
            }
            }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // // 添加图片
    // addPicture(file) {
    //   this.pictureList.push(file.file);
    //   console.log(this.pictureList, "添加");
    // },
    // // 删除列表图片
    // removePicture(file) {
    //   const index = this.pictureList.findIndex(item => {
    //     return item.uid === file.uid;
    //   });
    //   this.pictureList.splice(index, 1);
    //   console.log(this.pictureList, "删除");
    // },
    // 添加图片获取图片ID并绑定
    submitPicture(repairRecordCode) {
      // let form = new FormData();
      // console.log(this.pictureList);
      // this.pictureList.forEach(file => {
      //   form.append("multipartFiles", file);
      // });
      // // form.append('multipartFileList',this.pictureList)
      // form.append("repairRecordCode", repairRecordCode);
      RepairHandleApi.submitPicListNew({
        repairRecordCode: repairRecordCode,
        urlList: this.uploadPictureList.map(item => item.url)
      }).then(res => {
        console.log(res, "图片集合绑定");
      });
    },
    // 添加视频
    addVideo(file) {
      this.uploadVideoList.push(file.file);
      console.log(this.uploadVideoList, "添加");
    },
    // 删除列表视频
    removeVideo(file) {
      const index = this.uploadVideoList.findIndex(item => {
        return item.uid === file.uid;
      });
      this.uploadVideoList.splice(index, 1);
      console.log(this.uploadVideoList, "删除");
    },
    // 添加视频获取视频ID并绑定
    submitVideo(repairRecordCode) {
      // let videoIdList = [];
      // let uploadVideoListLength = this.uploadVideoList.length;
      // this.uploadVideoList.forEach(async item => {
      //   console.log(item);
      //   // let form = new FormData();
      //   // form.append("file", item);
      //   // form.append("videoName", item.name);
      //   const res = await videoApi.addEquipmentVideoNew({
      //     filePath: obj.url,
      //     fileName: obj.fileName
      //   });
        // if (res.code === 1) {
          // console.log(res);
          // videoIdList.push(res.data.equipmentVideoId);
          // if (uploadVideoListLength === videoIdList.length) {
            let params = {
              repairRecordCode: repairRecordCode,
              repairVideoIdList: this.equipmentVideoIdList
            };
            RepairHandleApi.repairTaskBindVideo(params).then(res => {
              console.log(res);
            });
          // }
        // } else {
        //   this.$message.error("视频添加失败");
        // }
      // });
    },
    // 查询可选择维修人
    queryUserList() {
      userApi.queryUserAll({}).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.userList = data;
        }
      });
    },
    // 点击添加按按钮
    addDeviceCodes() {
      let list = {
        deviceCode: "",
        num: "",
        cost: ""
      };
      this.$set(
        this.repairConsumeBOList,
        this.repairConsumeBOList.length,
        list
      );
      this.repairConsumeBOList = [...this.repairConsumeBOList];
    },
    // 删除改行
    delDeviceCodes(index) {
      this.repairConsumeBOList.splice(index, 1);
    },
    // 备件
    querySparePart() {
      // 获取数据
      let param = {
        // page: 1,
        // size: 1000,
        // entity: {
        //   input: 1
        // }
      };
      sparePartsInputApi.queryByCondition(param).then(res => {
        if (res.code === 1) {
          let data = res.data;
          this.sparePartArr = data;
        }
      });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          this.formData.repairTaskCode = this.editObject.repairTaskCode;
          this.formData.repairNature = "委内维修";
          this.repairConsumeBOList.forEach(a => {
            a.num = Number(a.num);
            var index = this.sparePartArr.findIndex(
              item => item.sparePartsCode === a.deviceCode
            );
            if (index !== -1) {
              a.deviceName = this.sparePartArr[index].sparePartsName;
            }
          });
          this.formData.repairConsumeBOList = this.repairConsumeBOList;
          this.formData.cost = Number(this.formData.cost);
          RepairHandleApi.addReIn(this.formData).then(async res => {
            if (res.code === 1) {
              if (this.uploadVideoList.length > 0) {
                await this.submitVideo(res.data);
              }
              if (this.uploadPictureList.length > 0) {
                await this.submitPicture(res.data);
              }
              this.$message.success("维修处理成功！");
              this.close();
            } else {
              this.$message.error("维修处理失败！");
            }
          });
        } else {
          return false;
        }
      });
    },
    close() {
      this.uploadVideoList = [];
      this.uploadPictureList = [];
      this.$emit("closeDialog");
    },
    cancel() {
      this.uploadVideoList = [];
      this.uploadPictureList = [];
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {

  .el-dialog__wrapper .el-dialog .el-dialog__body {
    max-height: 65vh;
    overflow-y: auto;
  }
}
.line-click {
  min-width: 30px;
  height: 30px;
  // background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  border: snow 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 5px;
  color: #fff;
  background-color: #003947;
  cursor: pointer;
}
.hang-content {
  width: 100%;
  .hang-content-one {
    width: 100%;
    display: flex;
  }
}

.add-many {
  border: 1px solid #6ecae3;
  width: 40px;
  height: 40px;
  padding: 0;
  background-color: transparent;
  line-height: 40px;
  border-radius: 4px;
  color: rgb(161, 154, 154);
  font-weight: 600;
  i {
    font-size: 40px;
  }
}
::v-deep .repairFile {
  width: 100%;
  display: flex;
  flex-direction: column;
  // .el-form-item {
  //   width: 50%;
  // }
}
</style>
